"""
日志配置
使用Loguru进行日志管理
"""
import sys
from pathlib import Path
from loguru import logger

from app.config import settings


def setup_logger():
    """
    配置日志系统
    
    特性：
    - 控制台输出彩色日志
    - 文件输出结构化日志
    - 自动日志轮转
    - 按日志级别过滤
    """
    # 移除默认的logger
    logger.remove()
    
    # 确保日志目录存在
    log_file = Path(settings.LOG_FILE)
    log_file.parent.mkdir(parents=True, exist_ok=True)
    
    # ==================== 控制台日志配置 ====================
    # 开发环境：彩色输出，详细信息
    if settings.ENV == "development":
        logger.add(
            sys.stdout,
            format=settings.LOG_FORMAT,
            level="DEBUG" if settings.DEBUG else "INFO",
            colorize=True,
            backtrace=True,  # 显示异常的完整traceback
            diagnose=True,   # 显示变量值
        )
    else:
        # 生产环境：简化输出
        logger.add(
            sys.stdout,
            format=settings.LOG_FORMAT,
            level=settings.LOG_LEVEL,
            colorize=True,
        )
    
    # ==================== 文件日志配置 ====================
    # 所有级别的日志
    logger.add(
        settings.LOG_FILE,
        format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} - {message}",
        level="DEBUG" if settings.DEBUG else "INFO",
        rotation=settings.LOG_ROTATION,      # 日志轮转
        retention=settings.LOG_RETENTION,     # 日志保留
        compression="zip",                    # 压缩旧日志
        encoding="utf-8",
        enqueue=True,                         # 异步写入
        backtrace=True,
        diagnose=True,
    )
    
    # ERROR级别单独记录
    error_log_file = log_file.parent / "error.log"
    logger.add(
        error_log_file,
        format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} - {message}",
        level="ERROR",
        rotation="100 MB",
        retention="60 days",
        compression="zip",
        encoding="utf-8",
        enqueue=True,
        backtrace=True,
        diagnose=True,
    )
    
    # ==================== 访问日志（可选）====================
    if settings.ENV == "production":
        access_log_file = log_file.parent / "access.log"
        logger.add(
            access_log_file,
            format="{time:YYYY-MM-DD HH:mm:ss} | {message}",
            level="INFO",
            rotation="1 day",
            retention="30 days",
            compression="zip",
            encoding="utf-8",
            filter=lambda record: "ACCESS" in record["extra"],
        )
    
    logger.info(f"日志系统初始化完成 | 环境: {settings.ENV} | 级别: {settings.LOG_LEVEL}")
    logger.info(f"日志文件: {settings.LOG_FILE}")


def log_request(method: str, path: str, status_code: int, duration: float):
    """
    记录API请求日志
    
    Args:
        method: HTTP方法
        path: 请求路径
        status_code: 状态码
        duration: 请求耗时（秒）
    """
    logger.bind(ACCESS=True).info(
        f"{method} {path} - {status_code} - {duration:.3f}s"
    )


def log_error(error: Exception, context: str = ""):
    """
    记录错误日志
    
    Args:
        error: 异常对象
        context: 上下文信息
    """
    logger.error(
        f"错误: {context} | 类型: {type(error).__name__} | 消息: {str(error)}",
        exc_info=True
    )


def log_performance(operation: str, duration: float, threshold: float = 1.0):
    """
    记录性能日志
    
    Args:
        operation: 操作名称
        duration: 耗时（秒）
        threshold: 警告阈值（秒）
    """
    if duration > threshold:
        logger.warning(f"性能警告: {operation} 耗时 {duration:.3f}s (阈值: {threshold}s)")
    else:
        logger.info(f"性能: {operation} 耗时 {duration:.3f}s")


# 导出logger实例供其他模块使用
__all__ = ["logger", "setup_logger", "log_request", "log_error", "log_performance"]







